# coding=utf-8
from webpack.DbMysql import DbMysql
from bottle import response, request, json_dumps, json_loads
import hashlib


class Home:
    def __init__(self):
        self.Db = DbMysql()

    def responseToRequest(self, json_array):
        response.content_type = 'application/json'
        response.body = json_dumps(json_array)
        return response

    def verifyAuth(self):
        key = "yixian_514d0521854ff51c497269f6b2522f42"
        allow_ips = ['127.0.0.1', '124.160.29.58', '118.31.67.111:22']
        sign = request.params.get("sign")
        timestamp = request.params.get("timestamp")
        ip = request.remote_addr
        if not sign or not timestamp:
            return False

        if ip not in allow_ips:
            return False
        m = hashlib.md5()
        m.update("{}{}".format(timestamp, key).encode("utf-8"))
        local_sign = m.hexdigest()
        if local_sign != sign:
            return False
        else:
            return True

    def getRoleInfo(self, role_id):
        sqlstr = "select * from rc_role where id=%s limit 1"
        result = self.Db.query(sqlstr, (role_id))
        return result

    def getUserInfo(self, uid):
        sqlstr = "select * from rc_user where uid=%s limit 1"
        result = self.Db.query(sqlstr, (uid))
        return result

    def getCurrentZone(self, uid):
        sqlstr = "select * from rc_user_current_zone where uid=%s limit 1"
        result = self.Db.query(sqlstr, (uid))
        return result

    def insertNew(self, sqlstr, args):
        return self.Db.execute(sqlstr, args)
